import merge from "webpack-merge";
import { Configuration, DefinePlugin, ProvidePlugin } from "webpack";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
// import { CleanWebpackPlugin } from "clean-webpack-plugin";
import { WebpackManifestPlugin } from "webpack-manifest-plugin";
import { getEntry, createHtmlWebpackPlugin, loadEnv } from "./webpack.utils";
import { resolveApp } from "./path";
const entrys = getEntry();
console.log("所有模块文件如下");
console.log(entrys);

//加载 .env.* 配置文件数据到 process.env
loadEnv();

export function getWebPackCommonConfig(mode: string): Configuration {
  return merge({
    mode: mode,
    devtool: "source-map",
    target: "web",
    entry: entrys,

    resolve: {
      alias: {
        "@src": resolveApp("src"),
      },
      extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
    },

    module: {
      strictExportPresence: true,
      rules: [
        {
          test: /\.(js|mjs|jsx|ts|tsx)$/, // 舍弃 babel , 使用 swc 性能比bable快 10 倍；
          exclude: /node_modules/,
          use: {
            loader: "swc-loader",
          },
        },

        {
          test: /.(sc|c)ss$/,
          use: [
            mode === "development"
              ? "style-loader"
              : MiniCssExtractPlugin.loader,
            {
              loader: "css-loader",
              options: {
                importLoaders: 2,
              },
            },
            "postcss-loader",
            "sass-loader",
          ],
        },
        // 图片类处理
        {
          test: /\.(png|gif|jpe?g|svg)$/,
          type: "asset", // webpack5使用内置静态资源模块，且不指定具体，根据以下规则 使用
          generator: {
            filename: "img/[name].[hash:8][ext]", // ext本身会附带 点，放入img目录下
          },
          parser: {
            dataUrlCondition: {
              maxSize: 10 * 1024, // 超过10kb的进行复制，不超过则直接使用base64
            },
          },
          // exclude: resolveApp("src/icons")
        },
        // 字体类处理
        {
          test: /\.(ttf|woff2?|eot)$/,
          type: "asset/resource", // 指定静态资源类复制
          generator: {
            filename: "font/[name].[hash:6][ext]", // 放入font目录下
          },
        },
      ],
    },

    plugins: [
      ...createHtmlWebpackPlugin(entrys),

      new ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
      }),

      new DefinePlugin({
        BASE_URL: '"./"',
        "process.env": JSON.stringify(process.env),
      }),

      new WebpackManifestPlugin({
        fileName: "asset-manifest.json",
      }),
    ],
  });
}
